<template>
  <!-- 角色显示界面 -->
  <el-table :data="roleList" border style="width: 100%">
    <el-table-column label="角色名称" width="180">
      <template v-slot="scoped">
        <a href="#" @click="save(scoped.row.roleName, scoped.row.roleId)">{{
          scoped.row.roleName
        }}</a>
      </template>
    </el-table-column>
    <el-table-column prop="createName" label="创建人" width="180" />
    <el-table-column prop="createTime" label="创建时间">
      <template v-slot="scoped">
        {{ scoped.row.createTime.substring(0, 10) }}
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" />
    <el-table-column prop="updateTime" label="修改时间">
      <template v-slot="scoped">
        {{
          scoped.row.updateTime ? scoped.row.updateTime.substring(0, 10) : ""
        }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="235">
      <template v-slot="scoped">
        <el-button
          type="warning"
          size="small"
          @click="Updatedata(scoped.row.roleId)"
          >修改</el-button
        >
        <el-button type="danger" size="small" @click="Del(scoped.row.roleId)"
          >删除</el-button
        >
        <el-button
          type="success"
          size="small"
          @click="FenPei(scoped.row.roleId, scoped.row.roleName)"
           
          >分配人员</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!--角色分配 对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisibleFenPei" width="500">
      <h3 style="margin-bottom: 33px">
        请设置<span style="color: red">【{{ ckrole.ckroleName }}】</span>
      </h3>
      <!-- 左右布局 -->
      <div class="common-layout">
        <el-container>
          <el-aside style="height: 300px; width: 200px">
            <!-- 部门加载 -->
            <div>
              <div>
                <el-tree
                  :data="DepData"
                  show-checkbox
                  node-key="value"
                  ref="treeRef"
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                  :default-checked-keys="defaultCheckedKeys"
                ></el-tree>
              </div>
            </div>
          </el-aside>
          <el-aside style="height: 300px; width: 200px">
            <!-- 用户根据部门加载 -->
            <div>
              <p>选择员工</p>
              <el-checkbox-group
                v-model="userrolevules.userIds"
                placeholder="选择员工"
              >
                <el-checkbox
                  v-for="items in uservule"
                  :key="items.userId"
                  :label="items.userName"
                  :value="items.userId"
                  
                />
              </el-checkbox-group>
              <!-- {{ userrolevules.userIds }} -->
            </div>
          </el-aside>
        </el-container>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleFenPei = false">取消</el-button>
          <el-button type="primary" @click="RoleUserAdd()"> 确定保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 角色对应的用户弹出框 -->
  <div>
    <el-dialog v-model="dialogFormVisible2" title="角色对应的用户" width="500">
      <h3>
        属于角色<span style="color: red"
          >【{{ ckrole.ckroleName }}】的员工如下</span
        >
      </h3>
   
      <el-table :data="getUserNamelist" border style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="userName" label="员工名称" width="180" />
        <el-table-column label="操作">
          <template v-slot="scoped">
            <el-button
              type="danger"
              size="small"
              @click="Delur(scoped.row.ruId)"
              >×</el-button
            >
            <el-button
              type="success"
              size="small"
              style="margin-top: 5px"
              @click="roleUserCor(scoped.row.roleid, scoped.row.roleName)"
              >+</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <el-pagination
    v-model:current-page="page.pageIndex"
    v-model:page-size="page.pageSize"
    :page-sizes="[8, 10, 15, 20]"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="page.totalCount"
  />
</template>

<script setup lang="ts">
import axios, { Axios } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import DepData from "@/stores/departmentData";
import { da } from "element-plus/es/locales.mjs";
const store = useCounterStore();
const router = useRouter();
const dialogFormVisible2 = ref(false);
const page = reactive({
  pageIndex: 1,
  pageSize: 15,
  totalCount: 0,
  totalPage: 0,
});

const roleList = ref([]);
const getroleList = () => {
  axios.get("https://localhost:7174/api/Message/GetRole", {
      params: {
        PageIndex: page.pageIndex,
        PageSize: page.pageSize,
      },
    })
    .then((res) => {
      //console.log(res.data)
      roleList.value = res.data.data;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
    });
};

//删除
const Del = (ids: number) => {
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .post("https://localhost:7272/api/Message/DelRole", {
          roleId: ids,
        })
        .then((res) => {
          if (res.data.code == 204) {
            ElMessage.success(res.data.msg);
            getroleList();
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

//修改跳转console
const Updatedata = (ids: any) => {
  console.log(ids);
  store.ccstore.uproleId = ids;
  router.push({
    name: "UpdateRole",
  });
};

//#region 对话框角色分配
//角色分配对话框开关
const dialogFormVisibleFenPei = ref(false);

//树形结构
const defaultProps = {
  children: "children",
  label: "label",
};

//部门信息存储
const Depvalue = ref([]);

//获取用户信息
const uservule = ref();
//选择保存用户ID
// const UserIdvalue = ref();
const treeRef = ref();
//部门id查询用户id
const handleCheckChange = () => {
  Depvalue.value = treeRef.value.getCheckedKeys();
  // console.log(treeRef.value.getCheckedKeys());
  const aa = <any>Depvalue.value.join(",");
  // console.log(aa);
  axios
    .get("https://localhost:7174/api/Message/GetUserNameByDepId", {
      params: {
        DepId: aa,
      },
    })
    .then((res) => {
      uservule.value = res.data.data;
    });
};

//添加用户角色数据
const userrolevules = reactive({
  roleId: 0,
  userIds: [],
  
});

//分配人员
const FenPei = (roleids: any, roleName: any) => {
  // console.log(ckrole.ckroleName);
  // console.log(roleids);
  roleNamefen.value = roleName;
//  console.log(roleNamefen.value,"roleNamefen.value ");

  dialogFormVisibleFenPei.value = true;
  userrolevules.roleId = roleids;
     // 清空 defaultCheckedKeys 的方法
  clearCheckedKeys();
  fenpeiuserromedep(roleids);
};
const defaultCheckedKeys=ref<any>([]);
const fenpeiuserromedep = (roleids: any) => {
  defaultCheckedKeys.value = [];
 Depvalue.value = [];
  axios.get("https://localhost:7174/api/Message/UserRoledep/UserRoledep", { params: { roleid: roleids} })
    .then((res) => {
         const data = res.data.data
    //反填用户
    const userids = data.map((x: any) => x.userId)
    // 设置默认选中的用户ID
      userrolevules.userIds = userids

    // console.log(userids, '反填用户ids')
    //反填部门
      const depids = data.map((x: any) => x.depId);
    // console.log(depids, '反填部门ids')
      const depIdVule = [...new Set(depids)];
      
    // console.log(depIdVule, '反填部门ids')
      defaultCheckedKeys.value = depIdVule
  
    })
}

//清空所选部门
const clearCheckedKeys = () => {
  defaultCheckedKeys.value = [];
  if (treeRef.value) { 
    console.log(treeRef.value, '清空')
    treeRef.value.setCheckedKeys([]);
    // console.log( treeRef.value.setCheckedKeys([]), '清空')

  }
}

//批量添加
const RoleUserAdd = () => {
    roleUserCor;
  // console.log(userrolevules);
    console.log(userrolevules.roleId, "批量删除的角色id")
  console.log(userrolevules.userIds, "批量添加的用户id")
  // 1、通过角色ID 批量删除
  axios.put("https://localhost:7272/api/Message/RemoveRole", userrolevules)
  .then((res) => {
    if (res.data.code == 204) {
      // console.log(res.data.msg);
    }
  })
  // 2、批量添加
  axios
    .post("https://localhost:7272/api/Message/PLAdd", userrolevules)
    .then((res) => {
      if (res.data.code == 214) {
          ElMessage.success(res.data.msg);
          dialogFormVisibleFenPei.value = false;
      } else {
        ElMessage.success(res.data.msg);
      }
    });
  dialogFormVisibleFenPei.value = false;
};
const diaroleName = ref([]);
// 添加角色对应的员工名-跳转到员工分配页面
const roleUserCor = (roleids:any, roleName:any) => {
  dialogFormVisibleFenPei.value = true;
  FenPei(roleids, roleName)
  diaroleName.value = roleName;
  console.log(diaroleName.value, "角色名");
};
//#endregion

//#region 修改对话框

//对话框 开关
const dialogFormVisibleUpdate = ref(false);

//#region 点击角色查看对应的用户
const ckrole = reactive({
  ckroleId: 0,
  ckroleName: "",
});
const roleNamefen=ref("")
const getUserNamelist = ref([]);
//角色名称
const save = (roleName: any, roleId: number) => {
    // console.log(ids);
  userrolevules.roleId = roleId;
  // console.log(userrolevules.roleId);
  dialogFormVisible2.value = true;
  ckrole.ckroleId = roleId;
  // console.log(ckrole.ckroleId);
  ckrole.ckroleName = roleName;

  getroleuserList();
  // Delur( ckrole.ckroleId);
};
//点击角色名称查看用户列表
const getroleuserList = () => {
  axios
    .get("https://localhost:7174/api/Message/GetUserNameByRoleId", {
      params: {
        RoleId: ckrole.ckroleId,
      },
    })
    .then((res) => {
      getUserNamelist.value = res.data.data;
    });
};

// 删除角色对应的用户名称--批删
const Delur = (ids: number) => {
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .put("https://localhost:7272/api/Message/DelUR", {
          RUId: ids,
        })
        .then((res) => {
          if (res.data.code == 204) {
            ElMessage.success(res.data.msg);
            getroleuserList();
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
//#endregion

onMounted(() => {
  getroleList();
});

watch(page, () => {});
</script>
